package com.hbt.android.kotlin.ui.learn

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.hbt.android.kotlin.R
import com.hbt.android.kotlin.http.ApiService
import com.hbt.android.kotlin.http.Course
import com.hbt.android.kotlin.http.RetrofitTest
import com.hbt.android.kotlin.service.LearnBroadcastReceiverActivity
import com.hbt.android.kotlin.service.LearnServiceActivity
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_home.recycler_view
import kotlinx.android.synthetic.main.learn_fragment.*
import kotlinx.android.synthetic.main.learn_item_fragment.view.*
import org.w3c.dom.Text
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class LearnFragment : Fragment() {

    private val TAG = "LearnFragment"


    override fun onAttach(context: Context) {
        super.onAttach(context)
        Log.e(TAG, "onAttach ->")
        Log.e(TAG, "当Fragment被添加到Activity中会回调，只会被调用一次")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate ->")
        Log.e(TAG, "创建Fragment时调用，只会被调用一次")
        // 取出LearnActivity传递来的参数
        val intArgument = arguments?.getInt("code")
        val strArgument = arguments?.getString("msg")
        Log.e(TAG, "取出LearnActivity传递来的参数：${intArgument}，${strArgument}")
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.e(TAG, "onCreateView ->")
        Log.e(TAG, "每次创建，绘制Fragment的View组件时回调，会将显示的view返回")
        val textview = TextView(context)
        textview.text = "SecondFragment"
        textview.gravity = Gravity.CENTER
        return textview

//        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.e(TAG, "onViewCreated ->")
        val textView: TextView = view as TextView
        val tab = arguments?.getString("tab")
        textView.text = "当前切换的tab页是：${tab}"
        view.setOnClickListener {
            // 调用activity
//            startActivity(Intent(context, LearnServiceActivity::class.java))
            // 调用Broadcast
            startActivity(Intent(context, LearnBroadcastReceiverActivity::class.java))
        }
//        if (tab.equals("tab1")) {
//            view.setOnClickListener {
//                startActivity(Intent(context, LearnServiceActivity::class.java))
//            }
//        }
//        val intArgument = arguments?.getInt("code")
//        val strArgument = arguments?.getString("msg")
//        Log.e(TAG, "参数 - ${intArgument} ， ${strArgument}")
//        textView.text = "参数 - ${intArgument} ， ${strArgument}"
//        Log.e(TAG, "参数 - ${arguments?.getString("tab")}")


//        val adapter = LearnAdapter()
//        recycler_view.layoutManager = LinearLayoutManager(context)
//        recycler_view.adapter = adapter
//
//        tab_add_course.setOnClickListener{
//            val course: Course = Course(
//                "Android study",
//                "https://www.songyubao.com/static/book/assets/icon-android.jpeg",
//                "50%",
//                "Android RecycleView"
//            )
//            adapter.addCourse(course)
//            recycler_view.scrollToPosition(0)
//        }
//
//        tab_del_course.setOnClickListener{
//            adapter.delCourse(0)
//        }
//
//        tab_update_course.setOnClickListener{
//            val course: Course = Course(
//                "Android study",
//                "https://www.songyubao.com/static/book/assets/icon-android.jpeg",
//                "100%",
//                "Android RecycleView"
//            )
//            adapter.updateCourse(0, "100%")
//        }
//
//        RetrofitTest.create(ApiService::class.java)
//            .getStudy().enqueue(object : Callback<List<Course>> {
//                override fun onResponse(
//                    call: Call<List<Course>>,
//                    response: Response<List<Course>>
//                ) {
//                    Log.e("onResponse:", response.body()?.toString() ?: "response is null")
//                    response.body()?.let {
//                        adapter.setData(it)
//                    }
//                }
//
//                override fun onFailure(call: Call<List<Course>>, t: Throwable) {
//                    Log.e("onFailure:", t.localizedMessage ?: "unknown error")
//                }
//
//            })
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        Log.e(TAG, "onActivityCreated ->")
        Log.e(TAG, "当Fragment所在的Activity启动完成后调用")
    }

    override fun onStart() {
        super.onStart()
        Log.e(TAG, "onStart ->")
        Log.e(TAG, "启动Fragment时被调用")
    }

    override fun onResume() {
        super.onResume()
        Log.e(TAG, "onResume ->")
        Log.e(TAG, "恢复Fragment时被调用，onStart()方法后一定会调用onResume()方法onStart可见，onResume后才能交互")
    }

    override fun onPause() {
        super.onPause()
        Log.e(TAG, "onPause ->")
        Log.e(TAG, "暂停Fragment调用")
    }

    override fun onStop() {
        super.onStop()
        Log.e(TAG, "onStop ->")
        Log.e(TAG, "停止Fragment调用")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.e(TAG, "onDestroyView ->")
        Log.e(TAG, "销毁Fragment所包含的View组件时使用")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy ->")
        Log.e(TAG, "销毁Fragment时调用")
    }

    override fun onDetach() {
        super.onDetach()
        Log.e(TAG, "onDetach ->")
        Log.e(TAG, "将Fragment从Activity被删除/替换完成后回调该方法，onDestroy方法后一定会回调该方法，该方法只调用一次")
    }







    inner class LearnAdapter : RecyclerView.Adapter<LearnAdapter.LearnViewHolder>() {

        private val courses = mutableListOf<Course>()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LearnViewHolder {

            val view =
                LayoutInflater.from(context).inflate(R.layout.learn_item_fragment, parent, false)
            return LearnViewHolder(view)
        }

        override fun onBindViewHolder(holder: LearnViewHolder, position: Int) {
            val course = courses[position]
            val options = RequestOptions().transform(RoundedCorners(10))
//                .centerCrop()
            Glide.with(context!!).load(course.poster)
                .apply(options)
                .into(holder.itemView.item_course_poster)
//            holder.itemView.item_course_poster.setImageResource(R.drawable.icon_large1)
            holder.itemView.item_course_title.text = "[${position}]" + course.title
            holder.itemView.item_course_label.text = course.label
            holder.itemView.item_course_content.text = course.progress

        }

        override fun getItemCount(): Int {
            return courses.size
        }

        /**
         * 获取所有课程
         */
        fun setData(data: List<Course>) {
            if (data.isNotEmpty()) {
                courses.addAll(data)
                notifyDataSetChanged()
            }
        }

        /**
         * 添加课程
         */
        fun addCourse(course: Course) {
            courses.add(0, course)
//            notifyItemInserted(0)
            notifyDataSetChanged()

        }

        /**
         * 删除课程
         */
        fun delCourse(position: Int) {
            courses.removeAt(position)
//            notifyItemRemoved(position)
            notifyDataSetChanged()

        }

        /**
         * 修改课程
         */
        fun updateCourse(position: Int, progress: String) {
            val course = courses[position]
            course.progress = progress
//            notifyItemChanged(position)
            notifyDataSetChanged()

        }

        inner class LearnViewHolder(view: View): RecyclerView.ViewHolder(view){

        }

    }
}
